/** 
 etf建议书
 zhanghaitao
*/
import React, { PureComponent } from 'react';
import { PrimaryC, ModalC, AvailableAssetC, TradeHoldC } from '../../../comps';
import style from '../../InvestmentManage/EtfTradeNew/orderComps/index.less';
import EtfDeal from './etfProposal';
import BaseInfoC from '../../InvestmentManage/EtfTradeNew/orderComps/baseInfo';
import EtfStockC from '../../InvestmentManage/EtfTradeNew/orderComps/etfStock';
import { connect } from 'dva';
import { message } from 'antd';
import 'moment/locale/zh-cn';
class AddEtfOrder extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      tradingcode: undefined, //证券代码
      exchangecode: undefined, //交易市场
      portfolio: undefined, //组合id
      secuabbr: undefined, //证券名称
      currentAsset: {}, //当前资金
      holdAmount: {}, //持仓数量
      querys: {}, //二次确认的数据
      isShow: false, //是否显示二次确认弹窗
      fieldsValues: {}, //ETF建议书二次确认框数据
      currentUser: {}, // 获取用户
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'etfProposalM/getUserInfo',
      payload: {
        userId: localStorage.getItem('antd-pro-userId'),
      },
      callback: (res) => {
        if (res) {
          this.setState({
            currentUser: res,
          });
        }
      },
    });
  }
  //获取form表单数据并校验
  confirmClick = () => {
    const { currentUser } = this.state;
    if (!this.EtfDeal.etfBuySell.state.isCanOrder) {
      //在点击“提交”时，若组合未配置外部通道，则提示用户，并无法提交
      message.warning(this.props.errorSetMsg);
      return;
    }
    this.EtfDeal.formGroupThis.props.form.validateFieldsAndScroll((err, fieldsValues) => {
      if (!err) {
        this.setState({ fieldsValues: fieldsValues });
        this.EtfDeal.etfBuySell.formGroupThis.props.form.validateFieldsAndScroll((err, fieldsValue) => {
          if (!err) {
            fieldsValue.userid = currentUser.userId;
            fieldsValue.username = currentUser.name;
            fieldsValue.secuabbr = this.state.secuabbr;
            fieldsValue.secuabbr2 = this.state.secuabbr2;
            fieldsValue.parValueTotal = fieldsValue.zlprice;
            fieldsValue.tradingcode = this.state.tradingcode;
            fieldsValue.exchangecode = this.state.exchangecode;
            delete fieldsValue.zlprice;
            delete fieldsValue.zqdm;
            //二次确认弹窗
            if (this.state.isShow) {
              this.orderSave(fieldsValue);
            } else {
              this.setState({
                isShow: true,
                querys: fieldsValue,
              });
            }
          }
        });
      }
    });
  };

  //请求后台
  orderSave = (params) => {
    const { fieldsValues } = this.state;
    params.proposalName = fieldsValues.investProposalName;
    params.proposalWriteDate = fieldsValues.applyDate.format('YYYY-MM-DD');
    delete params.exchangeCode;
    this.props.dispatch({
      type: 'etfProposalM/addEtfProposal',
      payload: {
        ...params,
      },
      callback: (data) => {
        if (data) {
          this.cancelClick(); //初始化form表单
          this.handleCancel(); //关闭弹窗
        } else {
          this.handleCancel(); //关闭弹窗
        }
      },
    });
  };

  // 提交成功清空表单
  cancelClick = () => {
    //指令下达  重置表单
    this.EtfDeal.etfBuySell.formGroupThis.props.form.resetFields();
    this.EtfDeal.formGroupThis.props.form.resetFields(['investProposalName']);
    this.EtfDeal.etfBuySell.setState({
      isCanOrder: true,
      typeStuas: false,
    });
    this.tradingcodeOnChange({});
    this.portfolioOnChange(undefined);
  };

  //组合id变更
  portfolioOnChange = (e) => {
    this.setState({
      portfolio: e,
    });
  };

  //证券code变更 传入证券code和交易市场
  tradingcodeOnChange = (values) => {
    this.setState({
      tradingcode: values.tradingcode,
      exchangecode: values.exchangecode,
      secuabbr: values.secuabbr,
      secuabbr2: values.tradingcode + '-' + values.exchangecode + '-' + values.secuabbr,
    });
  };

  //二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };

  // 二次确认modal框
  showModal = () => {
    const { querys, isShow, fieldsValues, currentUser } = this.state;
    const { loading } = this.props;
    querys.investProposalName = fieldsValues.investProposalName;
    const modalProps = {
      visible: isShow,
      title: '基金买卖建议书',
      width: 1010,
      height: 375,
      className: 'confirmOrder',
      confirmLoading: loading.effects['etfProposalM/addEtfProposal'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.confirmClick} onCancel={this.handleCancel}>
        <EtfDeal type={'4'} info={querys} proposalType={3} currentUser={currentUser} />
      </ModalC>
    );
  };

  render() {
    const { tradingcode, exchangecode, portfolio } = this.state;
    return (
      <div className={style.etfOrder}>
        <div>
          <div>
            <div style={{ marginBottom: '20px' }}>
              <BaseInfoC tradingcode={tradingcode} exchangecode={exchangecode} maatApi={true} />
            </div>
            <div>
              <EtfStockC tradingcode={tradingcode} exchangecode={exchangecode} height={'286px'} maatApi={true} />
            </div>
          </div>
          <div>
            <div style={{ marginBottom: '20px' }}>
              <AvailableAssetC
                portfolio={portfolio}
                maatApi={true}
                onChange={(e) => {
                  this.setState({
                    currentAsset: e,
                  });
                }}
              />
            </div>
            <div style={{ marginBottom: '20px' }}>
              <TradeHoldC
                securityType={'9'} //ETF
                maatApi={true}
                portfolio={portfolio}
                tradingcode={tradingcode}
                exchangecode={exchangecode}
                onChange={(e) => {
                  this.setState(
                    {
                      holdAmount: e,
                    },
                    () => {
                      this.EtfDeal.etfBuySell.changeinvestmentType();
                    },
                  );
                }}
              />
            </div>
            <EtfDeal
              type={2}
              proposalType={3}
              onRef={(ref) => (this.EtfDeal = ref)}
              currentUser={this.state.currentUser}
              productOnChange={() => {}}
              portfolioOnChange={this.portfolioOnChange}
              tradingcodeOnChange={this.tradingcodeOnChange}
              position={this.state.holdAmount}
            />
            <div className={'btnOperate grayBg'}>
              <PrimaryC title={'提交'} onClick={this.confirmClick} />
            </div>
          </div>
        </div>
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
      </div>
    );
  }
}
export default connect(({ etfOrderM, loading, isAccountConfiguredM }) => ({
  etfOrderM,
  loading,
  errorSetMsg: isAccountConfiguredM.msg,
}))(AddEtfOrder);
